package com.xuecheng.media.service.impl;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.api.content.agent.ContentApiAgent;
import com.xuecheng.api.content.model.dto.TeachplanMediaDTO;
import com.xuecheng.api.media.model.dto.MediaDTO;
import com.xuecheng.api.media.model.qo.QueryMediaModel;
import com.xuecheng.common.domain.page.PageRequestParams;
import com.xuecheng.common.domain.page.PageVO;
import com.xuecheng.common.domain.response.RestResponse;
import com.xuecheng.common.enums.common.AuditEnum;
import com.xuecheng.common.enums.common.ResourceTypeEnum;
import com.xuecheng.common.exception.ExceptionCast;
import com.xuecheng.common.util.StringUtil;
import com.xuecheng.media.common.constant.MediaErrorCode;
import com.xuecheng.media.common.utils.AliyunVODUtil;
import com.xuecheng.media.convert.MediaConvert;
import com.xuecheng.media.entity.Media;
import com.xuecheng.media.mapper.MediaMapper;
import com.xuecheng.media.service.MediaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 媒资信息 服务实现类
 * </p>
 *
 * @author 黄子弟
 */
@Slf4j
@Service
public class MediaServiceImpl extends ServiceImpl<MediaMapper, Media> implements MediaService {

    @Value("${aliyun.region}")
    private String regionId;
    @Value("${aliyun.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.accessKeySecret}")
    private String accessKeySecret;

    @Autowired
    private ContentApiAgent contentApiAgent;

    /*
     * 业务分析：
     *   1.判断关键
     *       companyid  filename  fileid(videoId)
     *   2.给信息数据赋值默认值
     *       auditStatus：未审核
     *
     *   3.保存信息
     *   4.将数据库最新数据返回
     *
     * */
    @Override
    @Transactional
    public MediaDTO createMedia(MediaDTO mediaDTO) {
        //关键数据
        if (ObjectUtils.isEmpty(mediaDTO.getCompanyId()) ||
                ObjectUtils.isEmpty(mediaDTO.getFilename()) ||
                ObjectUtils.isEmpty(mediaDTO.getFileId())) {
            ExceptionCast.cast(MediaErrorCode.E_140008);
        }

        //给信息数据赋值默认值
        mediaDTO.setAuditStatus(AuditEnum.AUDIT_UNPAST_STATUS.getCode());
        //保存媒体资源信息
        Media media = MediaConvert.INSTANCE.dto2entity(mediaDTO);
        boolean save = this.save(media);
        if (!save) {
            ExceptionCast.cast(MediaErrorCode.E_140001);
        }

        Media po = this.getById(media.getId());
        MediaDTO dto = MediaConvert.INSTANCE.entity2dto(po);
        return dto;

    }


    @Override
    public PageVO<MediaDTO> queryMediaList(PageRequestParams params, QueryMediaModel model, Long companyId) {
        /*
         *具体业务实现流程
         *  1.判断关键数据是否合法（分页数据）
         *  2.创建分页对象
         *  3.创建条件查询对象,并设置条件
         *  4.查询数据
         *  5.封装查询到的数据至PageVO对象并返回
         */

        //1.判断关键数据是否合法（分页数据）
        if (params.getPageNo() < 1) {
            params.setPageNo(PageRequestParams.DEFAULT_PAGE_NUM);
        }
        if (params.getPageSize() < 1) {
            params.setPageSize(PageRequestParams.DEFAULT_PAGE_SIZE);
        }

        //2.创建分页对象
        Page<Media> page = new Page<>(params.getPageNo(), params.getPageSize());

        //3.创建条件查询对象，,并设置条件
        LambdaQueryWrapper<Media> wrapper = Wrappers.lambdaQuery(Media.class);
        wrapper.like(StringUtil.isNotBlank(model.getFilename()), Media::getFilename, model.getFilename());
        wrapper.eq(StringUtil.isNotBlank(model.getType()), Media::getType, model.getType());
        wrapper.eq(StringUtil.isNotBlank(model.getAuditStatus()), Media::getAuditStatus, model.getAuditStatus());


        if (!companyId.equals(AuditEnum.COMPANY_ID)) {
            wrapper.eq(Media::getCompanyId, companyId);
        }


        //4.查询数据
        page = this.page(page, wrapper);

        //4.1将得到的pos转换为dtos
        List<Media> records = page.getRecords();
        List<MediaDTO> mediaDTOS = Collections.emptyList();
        if (!CollectionUtils.isEmpty(records)) {
            mediaDTOS = MediaConvert.INSTANCE.entitys2dtos(records);
        }

        //5.封装查询到的数据至PageVO对象并返回
        ///未转换dto之前的数据封装
        // PageVO<CourseBase> courseBases = PageVoUtil.getPageBean(courseBasePage, params);

        PageVO<MediaDTO> pageVO = new PageVO<>(mediaDTOS, page.getTotal(), params.getPageNo(), params.getPageSize());

        return pageVO;
    }

    @Override
    public String previewMedia(Long mediaId, Long companyId) {

        //关键数据

        if (ObjectUtils.isEmpty(mediaId) || ObjectUtils.isEmpty(companyId)) {
            ExceptionCast.cast(MediaErrorCode.E_140008);
        }

        //业务数据
        LambdaQueryWrapper<Media> wrapper = Wrappers.lambdaQuery(Media.class);
        wrapper.eq(Media::getId, mediaId);
        if (!companyId.equals(AuditEnum.COMPANY_ID)) {
            wrapper.eq(Media::getCompanyId, companyId);
        }
        Media media = this.getOne(wrapper);
        if (ObjectUtils.isEmpty(media)) {
            ExceptionCast.cast(MediaErrorCode.E_140005);
        }
        String url = "";
        try {
            String type = media.getType();
            if (type.equals(ResourceTypeEnum.VIDEO.getCode())) {
                //是视频
                DefaultAcsClient client = AliyunVODUtil.initVodClient(regionId, accessKeyId, accessKeySecret);
                GetPlayInfoResponse response = AliyunVODUtil.getPlayInfo(client, media.getFileId());
                List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList();
                if (!ObjectUtils.isEmpty(playInfoList)) {
                    url = playInfoList.get(0).getPlayURL();
                }
            }
        } catch (Exception e) {
            ExceptionCast.cast(MediaErrorCode.E_140012);
            return null;
        }
        return url;
    }

    @Override
    @Transactional
    public void deleteMedia(Long mediaId, Long companyId) {
        //关键数据
        //todo:异常没有准确定义，之后可以改一下
        if (ObjectUtils.isEmpty(mediaId) || ObjectUtils.isEmpty(companyId)) {
            ExceptionCast.cast(MediaErrorCode.E_140008);
        }


        //业务数据
        LambdaQueryWrapper<Media> wrapper = Wrappers.lambdaQuery(Media.class);
        wrapper.eq(Media::getId, mediaId).eq(Media::getCompanyId, companyId);
        Media media = this.getOne(wrapper);
        if (ObjectUtils.isEmpty(media)) {
            ExceptionCast.cast(MediaErrorCode.E_140005);
        }

        String auditStatus = media.getAuditStatus();
        if (auditStatus.equals(AuditEnum.AUDIT_PASTED_STATUS.getCode())) {
            ExceptionCast.cast(MediaErrorCode.E_140009);
        }

        //判断媒资信息是否有绑定课程计划
        RestResponse<TeachplanMediaDTO> response = contentApiAgent.getById(mediaId);
        if (!ObjectUtils.isEmpty(response.getResult())) {
            ExceptionCast.cast(MediaErrorCode.E_140003);
        }

        boolean remove = this.remove(wrapper);
        if (!remove) {
            ExceptionCast.cast(MediaErrorCode.E_140002);
        }

        try {
            DefaultAcsClient client = AliyunVODUtil.initVodClient(regionId, accessKeyId, accessKeySecret);
            AliyunVODUtil.deleteVideo(client, media.getFileId());
        } catch (Exception e) {
            ExceptionCast.cast(MediaErrorCode.E_140002);
        }
    }
}
